package org.fastsyncer.manager.framework;

import org.fastsyncer.manager.store.DataCenter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskLogHandle extends Thread  {
	
	private static Logger logger = LoggerFactory.getLogger(TaskLogHandle.class);

	private String taskName;
	
	private JSONObject handle;
	
	TaskLogHandle() {
		setName("fastsyncer task log thread");
	}
	
	/**
	 * 记录同步日志
	 * 
	 * @param taskName
	 *            任务名称
	 * @param handle
	 *            日志
	 */
	public TaskLogHandle(String taskName, JSONObject handle) {
		this.taskName = taskName;
		this.handle = handle;
	}
	
	@Override
	public void run() {
		try {
			JSONArray jsonArray = handle.getJSONArray("reason");
			int errSize = jsonArray.length();
			if (errSize > 0) {
				StringBuilder r = new StringBuilder();
				for (int i = 0; i < errSize; i++) {
					r.append(jsonArray.get(i) + "\n");
				}
				// 3.2持久化错误日志
				boolean store = DataCenter.getInstance().storeMappingLog(taskName, r);
				if (!store) {
					logger.error("Persistent storage error log failed!");
				}
			}
		} catch (JSONException e) {
			logger.error("Persistent storage error log failed:" + e.getCause());
		}
	}

}
